//
//  ViewController.m
//  PrintDemo
//
//  Created by Mac on 5/28/21.
//

#import "ViewController.h"
#import "PrinterBluetoothManager.h"
#import "BluetoothController.h"
#import "PrintfESCManager.h"
#import "ESCTable.h"
@interface ViewController ()

@property(strong,nonatomic) UILabel *titleLabel, *printTextLabel,*printBarcodeLabel,*printImageLabel, *printQRCodeImageLabel,*printQRCodeCommandLabel, *printTableLabel,*printNoteLabel, *blueNameUILabel;

@property PrinterBluetoothManager *printerBluetoothManager;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.printerBluetoothManager = [PrinterBluetoothManager printerBluetoothManagerInstance];
    [self.printerBluetoothManager setIsOpenDefaultConnect:NO];
    [self initView];
    [self addGesture];
}

- (void)viewWillAppear:(BOOL)animated{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.blueNameUILabel.text = [self.printerBluetoothManager getCurrentName] == NULL ? @"bluetooth not connected" : [self.printerBluetoothManager getCurrentName];
    });
    
}

-(void)initView{
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    CGFloat endY = STATUSBAR_HEIGHT;
    
    endY = [self initTitleLabel:endY];
    
    endY = [self initPrintTextLabel:endY + 10];
    
    endY = [self initPrintBarCodeLabel:endY + 10];
    
    endY = [self initPrintQRCodeImageLabel:endY + 10];
    
    endY = [self initPrintQRCodeCommandLabel:endY + 10];
    
    endY = [self initPrintImageLabel:endY + 10];
    
    endY = [self initPrintTableLabel:endY + 10];
    
    endY = [self initPrintNoteLabel:endY + 10];
    
    endY = [self initBlueNameLabel:endY];
}

-(void)addGesture{
    [self.printTextLabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *printTextLabelGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printTextAction:)];
    [self.printTextLabel addGestureRecognizer:printTextLabelGestureRecognizer];
    
    [self.printBarcodeLabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *printBarcodeLabelGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printBarCodeAction:)];
    [self.printBarcodeLabel addGestureRecognizer:printBarcodeLabelGestureRecognizer];
    
    [self.printQRCodeImageLabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *printQRCodeImageGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printQRCodeImageAction:)];
    [self.printQRCodeImageLabel addGestureRecognizer:printQRCodeImageGestureRecognizer];
    
    [self.printQRCodeCommandLabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *printQRCodeCommandGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printQRCodeCommandAction:)];
    [self.printQRCodeCommandLabel addGestureRecognizer:printQRCodeCommandGestureRecognizer];
    
    [self.printImageLabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *printImageLabelGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printImageAction:)];
    [self.printImageLabel addGestureRecognizer:printImageLabelGestureRecognizer];
    
    [self.printTableLabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *printTableLabelGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printTableAction:)];
    [self.printTableLabel addGestureRecognizer:printTableLabelGestureRecognizer];
    
    [self.printNoteLabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *printNoteLabelGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printNoteAction:)];
    [self.printNoteLabel addGestureRecognizer:printNoteLabelGestureRecognizer];

    [self.blueNameUILabel setUserInteractionEnabled:true];
    UITapGestureRecognizer *blueNameTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoConnectBlueAction:)];
    [self.blueNameUILabel addGestureRecognizer:blueNameTapGestureRecognizer];
}

//Print Text
-(void)printTextAction:(UITapGestureRecognizer *)recognizer{
    if(![self.printerBluetoothManager isConnected]){
        NSLog(@"Bluetooth is not connected");
        [self gotoConnectBlueAction:NULL];
        return;
    }
    // 获取一个ESC控制器实例
    // Get an ESC controller instance
    PrintfESCManager* instance = [PrintfESCManager createNew];
    // 清空数据
    // Clear data
    [instance clearData];
    // 初始化打印机
    // Initialize the printer
    [instance initPrinter];
    // 文本加粗
    // Bold text
    //[instance setBoldMode:1];
    // 内容居中对齐
    // Align the content to the center
    //[instance setSelectJustification:1];
    //[instance setLineSpace:0];
    // 设置打印的文本
    // Set the printed text
    [instance setBoldMode:1];
    [instance setText:@"A good"];
    [instance setPrint];
    [instance setBoldMode:0];
    [instance setText:@"A good medicine tasks bitter.Success often depends upon knowing how long it will take to succeed.Wise men learn by other men's mistakes.I wish I bad a different life. I wish I was braver and prettier or just happy. But it's useless to dream, because nothing ever changes.The blues are because you're getting far or maybe it's been raining too long."];
    [instance setText:@"\n\n\n\n\n\n"];
    // 发送数据给打印机
    // Send data to the printer
    [self.printerBluetoothManager writeNSData:[instance getData]];
    Byte readPaperState[] = {0x10,0x04,0x04};
    [self.printerBluetoothManager writeAndRead:[[NSData alloc]initWithBytes:readPaperState length:3] readNSData:^(NSData* returndata, NSString* returndatastring) {
        if(returndata.length > 0){
            Byte* bytes = (Byte *)returndata.bytes;
            if(bytes[0] == 0x12 || bytes[0] == 0x00){
                NSLog(@"Print successfully");
            }else{
                NSLog(@"Out of paper");
            }
        }else{
            NSLog(@"No data returned");
        }
    }];
}

//Print BarCode
-(void)printBarCodeAction:(UITapGestureRecognizer *)recognzier{
    if(![self.printerBluetoothManager isConnected]){
        NSLog(@"Bluetooth is not connected");
        [self gotoConnectBlueAction:NULL];
        return;
    }
    PrintfESCManager* instance = [PrintfESCManager createNew];
    [instance clearData];
    [instance initPrinter];
    [instance setSelectJustification:ALIGNLETF];
    [instance setText:@"UPC-A"];
    [instance setPrint];
    [instance setBarCodeWithType:BarCodeTypeUPCA barcodeStringPosition:BarCodePositionTypeBELOW barcodeHeightInDot:72 barcodeWidth:3 barcodeContent:@"123456789012"];
    [instance setPrint];
    [instance setText:@"EAN13"];
    [instance setPrint];
    [instance setBarCodeWithType:BarCodeTypeEAN13 barcodeStringPosition:BarCodePositionTypeBELOW barcodeHeightInDot:72 barcodeWidth:3 barcodeContent:@"1234567890128"];
    [instance setPrint];
    [instance setText:@"EAN8"];
    [instance setPrint];
    [instance setBarCodeWithType:BarCodeTypeEAN8 barcodeStringPosition:BarCodePositionTypeBELOW barcodeHeightInDot:72 barcodeWidth:3 barcodeContent:@"12345670"];
    [instance setPrint];
    [instance setText:@"CODE39"];
    [instance setPrint];
    [instance setBarCodeWithType:BarCodeTypeCODE39 barcodeStringPosition:BarCodePositionTypeBELOW barcodeHeightInDot:72 barcodeWidth:3 barcodeContent:@"123456"];
    [instance setPrint];
    [instance setText:@"CODEBAR"];
    [instance setPrint];
    [instance setBarCodeWithType:BarCodeTypeCODABAR barcodeStringPosition:BarCodePositionTypeBELOW barcodeHeightInDot:72 barcodeWidth:3 barcodeContent:@"123456"];
    [instance setPrint];
    [instance setText:@"CODE93"];
    [instance setPrint];
    [instance setBarCodeWithType:BarCodeTypeCODE93 barcodeStringPosition:BarCodePositionTypeBELOW barcodeHeightInDot:72 barcodeWidth:3 barcodeContent:@"123456"];
    [instance setPrint];
    [instance setText:@"CODE128"];
    [instance setPrint];
    [instance setBarCodeWithType:BarCodeTypeCODE128 barcodeStringPosition:BarCodePositionTypeBELOW barcodeHeightInDot:72 barcodeWidth:2 barcodeContent:@"No.123456"];
    [instance setText:@"\n\n\n\n\n\n"];
    [self.printerBluetoothManager writeNSData:[instance getData]];
}

//Print QRCode by image
-(void)printQRCodeImageAction:(UITapGestureRecognizer*)recognizer{
    if(![self.printerBluetoothManager isConnected]){
        NSLog(@"Bluetooth is not connected");
        [self gotoConnectBlueAction:NULL];
        return;
    }
    UIImage *uiImage = [UIImage imageNamed:@"qrcode_small"];
    PrintfESCManager* instance = [PrintfESCManager createNew];
    [instance clearData];
    [instance initPrinter];
    [instance setImage:uiImage left:0];
    [instance setText:@"\n\n\n\n\n\n"];
    [self.printerBluetoothManager writeNSData:[instance getData]];
}

//Print QRCode by command
-(void)printQRCodeCommandAction:(UITapGestureRecognizer*)recognizer{
    if(![self.printerBluetoothManager isConnected]){
        NSLog(@"Bluetooth is not connected");
        [self gotoConnectBlueAction:NULL];
        return;
    }
    PrintfESCManager* instance = [PrintfESCManager createNew];
    [instance clearData];
    [instance initPrinter];
    [instance setQRCode:@"123456789012"];
    [instance setText:@"\n\n\n\n\n\n"];
    [self.printerBluetoothManager writeNSData:[instance getData]];
}

//Print Image
-(void)printImageAction:(UITapGestureRecognizer*)recognizer{
    if(![self.printerBluetoothManager isConnected]){
        NSLog(@"Bluetooth is not connected");
        [self gotoConnectBlueAction:NULL];
        return;
    }
    UIImage *uiImage = [UIImage imageNamed:@"goodwork"];
    int newWidth = 38 * 8;
    uiImage = [self reSizeImage:uiImage toSize:CGSizeMake(newWidth, (int)(newWidth * uiImage.size.height / uiImage.size.width))];
    PrintfESCManager* instance = [PrintfESCManager createNew];
    [instance clearData];
    [instance initPrinter];
    [instance setImage:uiImage left:0];
    [instance setText:@"\n\n\n\n\n\n"];
    [self.printerBluetoothManager writeNSData:[instance getData]];
}

//Print Table
-(void)printTableAction:(UITapGestureRecognizer*)recognizer{
    if(![self.printerBluetoothManager isConnected]){
        NSLog(@"Bluetooth is not connected");
        [self gotoConnectBlueAction:NULL];
        return;
    }
    int array[4] = {14, 6, 6, 6};
    ESCTable* table = [[ESCTable alloc] init:@"Name;Quantity;unit price;Amount" regularExpression:@";" columnWidthArray:array columnWidthLength:4];
    [table setColumnAlignRight:true];
    [table addRow:@"1,Coffee;2.00;5.00;10.00"];
    [table addRow:@"2,TableWare;2.00;5.00;10.00"];
    [table addRow:@"3,Griddle Frog;1.00;68.00;68.00"];
    [table addRow:@"4,Garlic;1.00;4.00;4.00"];
    [table addRow:@"5,Fried peanuts;1.00;5.00;5.00"];
    [table addRow:@"6,Rice;1.00;2.00;2.00"];
    PrintfESCManager* instance = [PrintfESCManager createNew];
    [instance clearData];
    [instance initPrinter];
    [instance setTable:table];
    [instance setText:@"\n\n\n\n\n\n"];
    [self.printerBluetoothManager writeNSData:[instance getData]];
}

//Print Note
-(void)printNoteAction:(UITapGestureRecognizer*)recognizer{
    if(![self.printerBluetoothManager isConnected]){
        NSLog(@"Bluetooth is not connected");
        [self gotoConnectBlueAction:NULL];
        return;
    }
    int array[4] = {14, 6, 6, 6};
    ESCTable* table = [[ESCTable alloc] init:@"Name;Quantity;unit price;Amount" regularExpression:@";" columnWidthArray:array columnWidthLength:4];
    [table setColumnAlignRight:false];
    [table addRow:@"Storage bags;10.00;1;10.00"];
    [table addRow:@"Wire hook;5.00;2;10.00"];
    [table addRow:@"Umbrella;5.00;3;15.00"];
    PrintfESCManager* instance = [PrintfESCManager createNew];
    [instance clearData];
    [instance initPrinter];
    [instance setSelectJustification:1];
    [instance setPrintMode:48];
    [instance setText:@"NingBo YueHu Shop"];
    [instance setPrint];
    [instance setSelectJustification:0];
    [instance setPrintMode:0];
    [instance setText:@"Shop Num:574001"];
    [instance setPrint];
    [instance setText:@"Receipt Num:S00003169"];
    [instance setPrint];
    [instance setText:@"Cashier Num:s004_s004"];
    [instance setPrint];
    [instance setText:@"Receipt Date:2012-06-17"];
    [instance setPrint];
    [instance setText:@"Print Time:2012-06-17 13:37:24"];
    [instance setPrint];
    [instance setTable:table];
    [instance setTwoColumn:@"Goods Quantity:" content:@"6.00" paperMM:48];
    [instance setTwoColumn:@"Total:" content:@"35.00" paperMM:48];
    [instance setTwoColumn:@"Payment:" content:@"100.00" paperMM:48];
    [instance setTwoColumn:@"Change:" content:@"65.00" paperMM:48];
    [instance setText:@"Company Name:The Jiangsu Yiwuyishi Houseware Co.,Ltd."];
    [instance setPrint];
    [instance setText:@"Company Site:www.jiangsu1510.com"];
    [instance setPrint];
    [instance setText:@"Address:Dongchang Road on the 12th,Ningbo City, Jiangsu Provicne"];
    [instance setPrint];
    [instance setText:@"TEL:0574-88222999"];
    [instance setPrint];
    [instance setText:@"Service Line:4008-567-567"];
    [instance setPrint];
    [instance setText:@"============================="];
    [instance setPrint];
    [instance setPrintMode:16];
    [instance setText:@"Thank you,welcome to come again!Demo Version!"];
    [instance setText:@"\n\n\n\n\n\n"];
    [self.printerBluetoothManager writeNSData:[instance getData]];
}


-(void)gotoConnectBlueAction:(UITapGestureRecognizer *)recognizer{
    BluetoothController *controller = [[BluetoothController alloc] init];
    controller.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:controller animated:true completion:nil];
}

-(CGFloat)initTitleLabel:(CGFloat)startY{
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.frame = CGRectMake(50, startY, SCREEN_WIDTH - 100, 35);
    self.titleLabel.text = @"Receipt Print";
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.titleLabel];
    return self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height;
}

-(CGFloat)initPrintTextLabel:(CGFloat)startY{
    self.printTextLabel = [[UILabel alloc] init];
    self.printTextLabel.text = @"Print Text";
    self.printTextLabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.printTextLabel.backgroundColor = UIColor.grayColor;
    self.printTextLabel.textColor = UIColor.whiteColor;
    self.printTextLabel.textAlignment = NSTextAlignmentCenter;
    self.printTextLabel.layer.cornerRadius = 10;
    self.printTextLabel.layer.masksToBounds = true;
    [self.view addSubview:self.printTextLabel];
    return self.printTextLabel.frame.origin.y + self.printTextLabel.frame.size.height;
}

-(CGFloat)initPrintBarCodeLabel:(CGFloat)startY{
    self.printBarcodeLabel = [[UILabel alloc] init];
    self.printBarcodeLabel.text = @"Print Bar Code";
    self.printBarcodeLabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.printBarcodeLabel.backgroundColor = UIColor.grayColor;
    self.printBarcodeLabel.textColor = UIColor.whiteColor;
    self.printBarcodeLabel.textAlignment = NSTextAlignmentCenter;
    self.printBarcodeLabel.layer.cornerRadius = 10;
    self.printBarcodeLabel.layer.masksToBounds = true;
    [self.view addSubview:self.printBarcodeLabel];
    return self.printBarcodeLabel.frame.origin.y + self.printBarcodeLabel.frame.size.height;
}

-(CGFloat)initPrintQRCodeImageLabel:(CGFloat)startY{
    self.printQRCodeImageLabel = [[UILabel alloc] init];
    self.printQRCodeImageLabel.text = @"Print QRCode(By Image)";
    self.printQRCodeImageLabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.printQRCodeImageLabel.backgroundColor = UIColor.grayColor;
    self.printQRCodeImageLabel.textColor = UIColor.whiteColor;
    self.printQRCodeImageLabel.textAlignment = NSTextAlignmentCenter;
    self.printQRCodeImageLabel.layer.cornerRadius = 10;
    self.printQRCodeImageLabel.layer.masksToBounds = true;
    [self.view addSubview:self.printQRCodeImageLabel];
    return self.printQRCodeImageLabel.frame.origin.y + self.printQRCodeImageLabel.frame.size.height;
}

-(CGFloat)initPrintQRCodeCommandLabel:(CGFloat)startY{
    self.printQRCodeCommandLabel = [[UILabel alloc] init];
    self.printQRCodeCommandLabel.text = @"Print QRCode(By Command)";
    self.printQRCodeCommandLabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.printQRCodeCommandLabel.backgroundColor = UIColor.grayColor;
    self.printQRCodeCommandLabel.textColor = UIColor.whiteColor;
    self.printQRCodeCommandLabel.textAlignment = NSTextAlignmentCenter;
    self.printQRCodeCommandLabel.layer.cornerRadius = 10;
    self.printQRCodeCommandLabel.layer.masksToBounds = true;
    [self.view addSubview:self.printQRCodeCommandLabel];
    return self.printQRCodeCommandLabel.frame.origin.y + self.printQRCodeCommandLabel.frame.size.height;
}

-(CGFloat)initPrintImageLabel:(CGFloat)startY{
    self.printImageLabel = [[UILabel alloc] init];
    self.printImageLabel.text = @"Print Image";
    self.printImageLabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.printImageLabel.backgroundColor = UIColor.grayColor;
    self.printImageLabel.textColor = UIColor.whiteColor;
    self.printImageLabel.textAlignment = NSTextAlignmentCenter;
    self.printImageLabel.layer.cornerRadius = 10;
    self.printImageLabel.layer.masksToBounds = true;
    [self.view addSubview:self.printImageLabel];
    return self.printImageLabel.frame.origin.y + self.printImageLabel.frame.size.height;
}

-(CGFloat)initPrintTableLabel:(CGFloat)startY{
    self.printTableLabel = [[UILabel alloc] init];
    self.printTableLabel.text = @"Print Table";
    self.printTableLabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.printTableLabel.backgroundColor = UIColor.grayColor;
    self.printTableLabel.textColor = UIColor.whiteColor;
    self.printTableLabel.textAlignment = NSTextAlignmentCenter;
    self.printTableLabel.layer.cornerRadius = 10;
    self.printTableLabel.layer.masksToBounds = true;
    [self.view addSubview:self.printTableLabel];
    return self.printTableLabel.frame.origin.y + self.printTableLabel.frame.size.height;
}

-(CGFloat)initPrintNoteLabel:(CGFloat)startY{
    self.printNoteLabel = [[UILabel alloc] init];
    self.printNoteLabel.text = @"Print Note";
    self.printNoteLabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.printNoteLabel.backgroundColor = UIColor.grayColor;
    self.printNoteLabel.textColor = UIColor.whiteColor;
    self.printNoteLabel.textAlignment = NSTextAlignmentCenter;
    self.printNoteLabel.layer.cornerRadius = 10;
    self.printNoteLabel.layer.masksToBounds = true;
    [self.view addSubview:self.printNoteLabel];
    return self.printNoteLabel.frame.origin.y + self.printNoteLabel.frame.size.height;
}



-(CGFloat)initBlueNameLabel:(CGFloat)startY{
    self.blueNameUILabel = [[UILabel alloc] init];
    self.blueNameUILabel.text = @"bluetooth not connected";
    self.blueNameUILabel.frame = CGRectMake(10, startY, SCREEN_WIDTH - 20, 50);
    self.blueNameUILabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:self.blueNameUILabel];
    return self.blueNameUILabel.frame.origin.y + self.blueNameUILabel.frame.size.height;
}

-(void)backAction:(UITapGestureRecognizer *)recognizer{
    [self dismissViewControllerAnimated:true completion:NULL];
}

-(UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reSizeImage;
}

@end
